import 'dart:async';

import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/surplus_market/sm_details/state.dart';
import 'package:yp/services/api.dart';

import '../../../../router.dart';

import 'package:fluwx/fluwx.dart' as fluwx;

class SMDetailsLogic extends GetxController {
  SMDetailsState state = SMDetailsState();
  Timer surplusTimer;

  String itemNumId;
  String styleNumId;
  String shopId;
  String cat1Id;
  String ecStyleNumId;

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
        styleNumId = Get.arguments['styleNumId'];
        shopId = Get.arguments['shopId'];
        cat1Id = Get.arguments['cat1Id'];
      }
    getSurplusMarketDetails();
  }

  void getSurplusMarketDetails() {
    var params = {
      'activity_id': Get.arguments['activity_id'],
      'item_num_id': Get.arguments['item_num_id'],
      "user_num_id": SpUtil.getInt('empeNumId'),
      "ec_shop_num_id":shopId,
      "channel_num_id": 99,
      "use_platform": 2,
    };
    print('params====$params');
    Api.surplusMarketDetails(params).listen((event) {
      if (event != null && event['code'] == 0) {
        state.details = event;
        DateTime time = DateTime.now();
        DateTime endTime = DateTime.parse(event['end_time']).toUtc();
        Duration different = endTime.difference(time);
        state.surplusTime = different.inSeconds;
        state.smWatchTimer=StopWatchTimer(
            mode:StopWatchMode.countDown,
            presetMillisecond:different.inMilliseconds,
        );
        state.smWatchTimer.onExecute.add(StopWatchExecute.start);
        state.ec_style_num_id = event['ec_style_num_id'];
        ecStyleNumId = event['ec_style_num_id'].toString();
        // startTimer();
        getAndGoThirdShop();
        requestRecommendGoods();
        requestImageAndContent();
      }
      update();
    });
  }
  void goToThirdShop() {
    SpUtil.remove(Config.GET_SHOP_INFO);
    SpUtil.putObject(Config.GET_SHOP_INFO, state.shopInfos);
    SpUtil.putInt(Config.IS_CHANGE_SHOP,
        SpUtil.getInt('storeShopNum').toString() == shopId ? 0 : 1);
    Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
  }

  void getAndGoThirdShop() {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString('token'),
      "ec_shop_num_id": shopId,
    };
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          var shoplistes = event['ec_shop_infos'];
          state.shopInfos = {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          };
          update();
        }
      } else {
        toast(event['massage']);
      }
    });
  }

  // 推荐商品
  void requestRecommendGoods() {
    var token = SpUtil.getString('token');
    if (token == null || token == '') return;
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "cat1_id": cat1Id,
      "is_recommend": 1,
      "shop_id": shopId,
      "shop_num_id": shopId,
      "page_no": 1,
      "page_size": 10,
      "access_token": SpUtil.getString('token')
    };
    Api.recommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        state.recommendGoods = event;
        update();
      }
    });
  }
  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId,
      {int quantity = 1}) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": state.nums,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": state.ec_style_num_id,
      'access_token': SpUtil.getString('token'),
    };
    print(params);
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        toast('加入购物车成功');
      } else {
        toast(event['message']);
      }
    });
  }

  // 商品规格信息
  void requestImageAndContent() {
    var params = {
      "use_platform": 2,
      "ec_style_num_id": ecStyleNumId,
      "type": "wap"
    };
    Api.goodsDetailImageAndContent(params).listen((event) {
      if (event['code'] == 0) {
        state.richText = event;
        update();
      }
    });
  }
  // 获取广告
  void getAdvertisingList() {
    var params = {
      'adv_category': 2,
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      print("广告：$event");
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
      } else {
        state.advertising = [];
      }
      update();
    });
  }

  void goShop() {
    if (SpUtil.getString('token') == null ||
        SpUtil.getString('token').isEmpty) {
      Get.toNamed(RouteConfig.mallLogin).then((value) {
        // if (SpUtil.getString('token') != null &&
        //     SpUtil.getString('token').isNotEmpty) {
        //   logic.requestDetail();
        // }
      });
    } else {
      Get.toNamed(RouteConfig.settleAccounts, arguments: {
        // Get.toNamed(RouteConfig.orderSettlements, arguments: {
        'shop_id': state.details['shop_num_id'],
        "item_num_id": state.details['item_num_id'],
        "style_num_id": state.details['style_num_id'],
        "ec_style_num_id": state.details['ec_style_num_id'],
        'shopnum': 1,
      });
    }
  }

  void goSurplusShop() {
    if (SpUtil.getString('token') == null ||
        SpUtil.getString('token').isEmpty) {
      Get.toNamed(RouteConfig.mallLogin).then((value) {
        // if (SpUtil.getString('token') != null &&
        //     SpUtil.getString('token').isNotEmpty) {
        //   logic.requestDetail();
        // }
      });
    } else {
      Get.toNamed(RouteConfig.sMSettlementPage, arguments: {
        "ecactivity_id": Get.arguments['activity_id'],
        'shop_id': state.details['shop_num_id'],
        "item_num_id": state.details['item_num_id'],
        "style_num_id": state.details['style_num_id'],
        "ec_style_num_id": state.details['ec_style_num_id'],
        'shopnum': 1
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }


  String constructTime(num mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return days.toString() +
        "天" +
        hours.toString() +
        "时" +
        minutes.toString() +
        "分" +
        seconds.toString() +
        "秒";
  }


  void shareToFriend() {
    var   data = 'pintuan/pages/superGoodsDetail?activity_id=${Get.arguments['activity_id']
    }&item_num_id=${Get.arguments['item_num_id']}&shopId=$shopId';
    WeChatImage img=WeChatImage.asset('assets/images/defaultAvatar_image.png');
    var title='超级团';
    var desc='超级团';
    if(state.details!=null ) {
      if (state.details['image_default_id'] != null &&
          state.details['image_default_id'] !='') {
        img =WeChatImage.network( state.details['image_default_id']);
      }
      if ( state.details['item_name']!=null &&  state.details['item_name']!='') {
        title =  state.details['item_name'];
        desc=title;
      }

    }
    var model = new WeChatShareMiniProgramModel(
      path: data,
      webPageUrl: 'www.baidu.com',
      userName: Config.MINI_ACCOUNT,
      miniProgramType:
      Config.isDev ? WXMiniProgramType.TEST : WXMiniProgramType.RELEASE,
      title: title,
      description: desc,
      thumbnail: img,
      hdImagePath: img,
    );
    fluwx.shareToWeChat(model);

  }
}
